<?php
//by willson 105328468@qq.com 2014/10/11
class passport extends core {
	public $member_mod;
	public function __construct() {
		parent::__construct();
		$this->member_mod = m('member');
	}

	//第三方快速登录
	public function third_login() {
		$udid = $this->request->post('udid');
		$source = trim($this->request->post('source'));
		$openid = trim($this->request->post('hash'));
		$where = "openid='{$openid}'";
		if ($source=='wechat') {
			$where = "openid='{$openid}'";
		} else if ($source=='qq') {
			$where = "qq_openid='{$openid}'";
		}
		$member = SQL::share('member')->where($where)->row();
		if ($member) {
			if ($member->status==1) {
				//推送强制下线通知
				if ($member->udid!='' && $member->udid!=$udid) {
					$this->notify->send($member->udid, "账号已在其他设备登录", "", "", array("action"=>"login", "state"=>-100), "ios");
				}

				$data = array();
				if ($udid!='') {
					SQL::share('member')->where("udid='{$udid}'")->update("udid=''");
				}
				$data['udid'] = $udid;
				$data['last_time'] = time();
				$data['last_ip'] = ip();
				$data['logins'] = array("logins", "+1");
				SQL::share('member')->where($member->id)->update($data);
				$this->_after_passport($member, true, false);
			} else {
				error("账号已经被冻结", -1);
			}
		} else {
			$_POST['is_mobile'] = 0;
			$_SESSION['member_temp'] = $_POST;
			success($_POST);
		}
	}

	//绑定手机
	public function set_mobile() {
		$mobile = $this->request->post('mobile');
		$code = $this->request->post('code');
		$password = $this->request->post('password');
		$session_mobile = $this->request->session('login_sms_mobile');
		$session_code = $this->request->session('login_sms_code');
		if ($mobile == '') error('手机号码不能为空');
		if ($code == '') error('手机验证码不能为空');
		if ($mobile != $session_mobile) error('手机号码不正确');
		if ($code != $session_code) error('手机验证码不正确');
		$member_temp = isset($_SESSION['member_temp']) ? $_SESSION['member_temp'] : null;
		if (!isset($_SESSION['member']) && !$member_temp) error('请先登录', -100);
		
		$salt = generate_salt();
		$is_login = false;
		$is_register = false;
		if (isset($_SESSION['member'])){
			$is_login = true;
			$set = '';
			$openid = $this->request->session('openid');
			if (!strlen($openid)) $set = ", openid='{$openid}'";
			if (!strlen($_SESSION['member']->salt)) {
				if ($password == '') error('密码不能为空');
				$crypt_password = crypt_password($password, $salt);
				SQL::share('member')->where($this->member_id)->update("password='{$crypt_password}', salt='{$salt}' {$set}");
			}
			SQL::share('member')->where($this->member_id)->update("mobile='{$mobile}' {$set}");
		} else if ($member_temp) {
			$_POST = $member_temp;
			$udid = $this->request->post('udid');
			$source = $this->request->post('source');
			$openid = $this->request->post('hash');
			$member = SQL::share('member')->where("mobile='{$mobile}'")->row();
			if ($member) {
				$is_login = true;
				$set = '';
				if ($source=='wechat') {
					$set = ", openid='{$openid}'";
				} else if ($source=='qq') {
					$set = ", qq_openid='{$openid}'";
				}
				if (!strlen($member->salt)) {
					if ($password == '') error('密码不能为空');
					$crypt_password = crypt_password($password, $salt);
					SQL::share('member')->where("mobile='{$mobile}'")->update("password='{$crypt_password}', salt='{$salt}' {$set}");
				}
				if ($udid!='') {
					SQL::share('member')->where("udid='{$udid}'")->update("udid=''");
				}
				SQL::share('member')->where("mobile='{$mobile}'")->update("udid='{$udid}' {$set}");
			} else {
				$is_register = true;
				if ($password == '') $password = random_str(8);
				$crypt_password = crypt_password($password, $salt);
				//微信的信息
				$nick_name = $this->request->post('nickname');
				$avatar = $this->request->post('headimgurl');
				$sex = $this->request->post('sex');
				$province = $this->request->post('province');
				$city = $this->request->post('city');
				
				//注册信息
				$data = array();
				$data['name'] = $mobile;
				$data['mobile'] = $mobile;
				$data['reg_time'] = time();
				$data['reg_ip'] = $this->ip;
				$data['last_time'] = time();
				$data['last_ip'] = $this->ip;
				$data['logins'] = 1;
				$data['status'] = 1;
				$data['udid'] = $udid;
				$data['salt'] = $salt;
				$data['password'] = $crypt_password;
				$data['nick_name'] = $nick_name;
				$data['sex'] = $sex;
				$data['province'] = $province;
				$data['city'] = $city;
				$data['avatar'] = $avatar;
				if ($source=='wechat') {
					$data['openid'] = $openid;
				} else if ($source=='qq') {
					$data['qq_openid'] = $openid;
				}
				
				if ($udid!='') {
					SQL::share('member')->where("udid='{$udid}'")->update("udid=''");
				}
				SQL::share('member')->insert($data);
			}
		}
		$_SESSION['member_temp'] = '';
		unset($_SESSION['member_temp']);
		
		$order_id = (isset($_SESSION['order_id']) && trim($_SESSION['order_id'])) ? intval($_SESSION['order_id']) : 0;
		if ($order_id) {
			$_SESSION['order_id'] = '';
			unset($_SESSION['order_id']);
			header("location:wap.php?tpl=order.complete&order_id={$order_id}");
			exit;
		}
		
		$member = SQL::share('member')->where("mobile='{$mobile}'")->row();
		if ($member) {
			$_SESSION['member'] = $member;
			$this->_check_login();
			$url = (isset($_SESSION['weixin_url']) && trim($_SESSION['weixin_url'])) ? trim($_SESSION['weixin_url']) : '';
			if ($url) {
				header("Location:{$url}");
				exit;
			}
			$this->_after_passport($member, $is_login, $is_register);
		} else {
			error("查询不到对应该手机号码的账号，请先注册");
			//echo '<meta charset="UTF-8"><script>alert("查询不到对应该手机号码的账号，请先注册");location.href="wap.php?app=register";< /script>';
			//header("location:wap.php?tpl=register");
			//exit;
		}
	}

	//微信端绑定手机号码
    public function member_mobile() {
        $mobile = $this->request->post('mobile');
        $member = SQL::share('member')->where("id='{$this->member_id}'")->row();
        //查找数据库有没有此手机号(pc，wap端网站先注册)
        $old_member = SQL::share('member')->where("mobile='{$mobile}'")->row();
        if ($old_member){
            //有的话把sign和openid转到该用户上
            SQL::share('member')->where("mobile='{$old_member->mobile}'")->update(array('sign'=>$member->sign, 'openid'=>$member->openid));
            //微信端用户改变sign和openid
            $sign = $member->sign.'test';
            $openid = $member->openid.'test';
            SQL::share('member')->where("id='{$member->id}'")->update(array('sign'=>$sign, 'openid'=>$openid));
            $this->member_id = $old_member->id;
        }else{
            SQL::share('member')->where("id='{$member->id}'")->update(array('mobile'=>$mobile));
        }
        script('绑定成功', 'wap.php?app=cart&act=info');
    }

	//登录
	public function login() {
		//$this->clearsession();
		if (isset($_SESSION['member'])) unset($_SESSION['member']);
		if (isset($this->member) && $this->member_id>0) $this->member_id = 0;
		$mobile = $this->request->post('mobile');
		$udid = $this->request->post('udid');
		//微信的信息
		$nick_name = $this->request->post('nick_name');
		$avatar = $this->request->post('avatar');
		$sex = $this->request->post('sex');
		$province = $this->request->post('province');
		$city = $this->request->post('city');
		//openid不为空，表示从微信访问过来，直接使用openid登录
		$member = "";
		$openid = trim($this->request->get('openid'));
		if ($this->is_weixin() && $this->weixin_authed() && $openid) { //增加判断$_GET['openid']为了区分是否主动登录
			$_SESSION['openid'] = $openid;
			$member = SQL::share('member')->where("openid='{$openid}'")->row();
			//var_dump($member);
			//exit;
		} else {
			if ($mobile == '') error('手机号码不能为空');
			$member = SQL::share('member')->where("mobile='{$mobile}'")->row();
			if (!$member) {
				//生成一个新的用户
                //注册信息
                $data = array();
                $data['name'] = $mobile;
                $data['mobile'] = $mobile;
                $data['reg_time'] = time();
                $data['reg_ip'] = $this->ip;
                $data['last_time'] = time();
                $data['last_ip'] = $this->ip;
                $data['logins'] = 1;
                $data['status'] = 1;
                $data['udid'] = $udid;
                $data['openid'] = $openid;
                $data['nick_name'] = $nick_name;
                $data['sex'] = $sex;
                $data['province'] = $province;
                $data['city'] = $city;
                $data['avatar'] = $avatar;
                if ($udid!='') {
                    //20150708 by ajsong 清除之前登录过的有相同udid的账号的udid
                    SQL::share('member')->where("udid='{$udid}'")->update("udid=''");
                }
                //20160222 by willson 绑定微信openid
                //20160322 by ajsong 增加更新头像,与微信同步
                if ($openid && isset($_SESSION['weixin'])) {
                    $data['nick_name'] = $_SESSION['weixin']->nickname;
                    $data['sex'] = $_SESSION['weixin']->sex;
                    $data['province'] = $_SESSION['weixin']->province;
                    $data['city'] = $_SESSION['weixin']->city;
                    $data['avatar'] = $_SESSION['weixin']->avatar;
                }
                //写入
                //微信登录,为兼容日后主动登录,所以把name记录为手机号码
                //print_r($data);
                //exit;
                SQL::share('member')->insert($data);
                //exit;
                $member_id = $this->db->insert_id;
                //生成新用户的邀请码
                $new_invite_code = 0;
                do {
                    //by willson 2016/3/7 随机数+id
                    $new_invite_code = rand(10000,50000) + $member_id;
                    $sql = "SELECT * FROM {$this->tbp}member WHERE invite_code='{$new_invite_code}'";
                } while ($this->db->get_row($sql));
                SQL::share('member')->where($member_id)->update("invite_code='{$new_invite_code}'");
                //
                $member = SQL::share('member')->where($member_id)->find();
                if (!$member) {
                    error("注册失败");
                }
			}
		}
		if ($member) {
			if ($member->status==1) {
				//推送强制下线通知
				if ($member->udid!='' && $member->udid!=$udid) {
					$this->notify->send($member->udid, "账号已在其他设备登录", "", "", array("action"=>"login", "state"=>-100), "ios");
				}

				$data = array();
				if ($udid!='') {
					//20150708 by ajsong 清除之前登录过的有相同udid的账号的udid
					SQL::share('member')->where("udid='{$udid}'")->update("udid=''");
				}
				$data['udid'] = $udid;

				//环信登录需要原始密码
				$data['last_time'] = time();
				$data['last_ip'] = ip();
				$data['logins'] = array("logins", "+1");
				SQL::share('member')->where($member->id)->update($data);
                header("location:wap.php?app=cart&act=info");
				$this->_after_passport($member, true, false);
			} else {
				error("账号已经被冻结", -1);
			}
		} else if ($this->is_weixin() && $this->weixin_authed() && $openid) {
			$url = (isset($_SESSION['weixin_url']) && trim($_SESSION['weixin_url'])) ? trim($_SESSION['weixin_url']) : 'wap.php';
			header("location:{$url}");
		}
	}

	//注册
	public function register() {
		//$this->clearsession();
		if (isset($_SESSION['member'])) unset($_SESSION['member']);
		if (isset($this->member) && $this->member_id>0) $this->member_id = 0;
		$mobile = $this->request->post('mobile');
		$password = $this->request->post('password');
		$code = $this->request->post('code');
		$invite_code = $this->request->post('invite_code');
		$udid = $this->request->post('udid');
		$session_code = $this->request->session('verify_code');
		$session_mobile = $this->request->session('verify_mobile');
		$salt = generate_salt();
		$crypt_password = crypt_password($password, $salt);
		//print_r($_SESSION);
		//微信的信息
		$nick_name = $this->request->post('nick_name');
		$avatar = $this->request->post('avatar');
		$sex = $this->request->post('sex');
		$province = $this->request->post('province');
		$city = $this->request->post('city');
		//openid不为空，表示从微信访问过来，直接使用openid登录
		$member = "";
		$openid = trim($this->request->post('openid'));
		if (!$openid) $openid = (isset($_SESSION['openid']) && trim($_SESSION['openid'])) ? trim($_SESSION['openid']) : '';
		//注册信息
		$data = array();
		$data['name'] = $mobile;
		$data['mobile'] = $mobile;
		$data['reg_time'] = time();
		$data['reg_ip'] = $this->ip;
		$data['last_time'] = time();
		$data['last_ip'] = $this->ip;
		$data['logins'] = 1;
		$data['status'] = 1;
		$data['udid'] = $udid;
		$data['invite_code'] = $invite_code;
		$data['origin_password'] = $password;
		$data['salt'] = $salt;
		$data['password'] = $crypt_password;
		$data['openid'] = $openid;
		$data['nick_name'] = $nick_name;
		$data['sex'] = $sex;
		$data['province'] = $province;
		$data['city'] = $city;
		$data['avatar'] = $avatar;

		if ($mobile == '') error('手机号码不能为空');
		if ($code == '') error('手机验证码不能为空');
		if ($password == '') error('密码不能为空');
		if ($code != $session_code) error('手机验证码不正确');
		if ($mobile != $session_mobile) error('手机号码不正确');
		//注册
		if (SQL::share('member')->where("mobile='{$mobile}'")->exist()) {
			error("手机号码已经被注册");
		}

		$reseller_id = (isset($_SESSION['reseller_id']) && trim($_SESSION['reseller_id'])) ? trim($_SESSION['reseller_id']) : '';
		if ($invite_code) {
			$invitor = SQL::share('member')->where("invite_code='{$invite_code}'")->row();
			if (!$invitor) {
				error("邀请码无效");
			}
			//邀请人id
			$data['parent_id'] = $invitor->id;
		} else if ($reseller_id) {
			$data['parent_id'] = $reseller_id;
		}
		if ($udid!='') {
			//20150708 by ajsong 清除之前登录过的有相同udid的账号的udid
			SQL::share('member')->where("udid='{$udid}'")->update("udid=''");
		}
		//20160222 by willson 绑定微信openid
		//20160322 by ajsong 增加更新头像,与微信同步
		if ($openid && isset($_SESSION['weixin'])) {
			$data['nick_name'] = $_SESSION['weixin']->nickname;
			$data['sex'] = $_SESSION['weixin']->sex;
			$data['province'] = $_SESSION['weixin']->province;
			$data['city'] = $_SESSION['weixin']->city;
			$data['avatar'] = $_SESSION['weixin']->avatar;
		}
		//写入
		//微信登录,为兼容日后主动登录,所以把name记录为手机号码
		//print_r($data);
		//exit;
		SQL::share('member')->insert($data);
		//exit;
		$member_id = $this->db->insert_id;
        //生成新用户的邀请码
        $new_invite_code = 0;
        do {
            //by willson 2016/3/7 随机数+id
            $new_invite_code = rand(10000,50000) + $member_id;
            $sql = "SELECT * FROM {$this->tbp}member WHERE invite_code='{$new_invite_code}'";
        } while ($this->db->get_row($sql));
        SQL::share('member')->where($member_id)->update("invite_code='{$new_invite_code}'");
        //
		$member = SQL::share('member')->where($member_id)->find();
		if (!$member) {
			error("注册失败");
		}
		$this->_after_passport($member, false, true);
	}

	//主动调用微信登录
	public function wx_login(){
		//20160322 by ajsong 先判断是否已经进行认证(因为有可能是认证返回到这个接口)
		if ($this->is_weixin() && $this->weixin_authed()) {
			header("Location:api.php?app=passport&act=login&openid=".$_SESSION['openid']); //需要使用header跳转,为了指定当前不是主动登录
		} else {
			if ($this->is_weixin()) {
				$url = (isset($_SESSION['weixin_url']) && trim($_SESSION['weixin_url'])) ? trim($_SESSION['weixin_url']) : 'wap.php';
				header("location:{$url}"); //因为非微信端不能使用认证登录
			} else {
				$this->weixin_login(); //进行认证跳转
			}
		}
		exit;
	}

	public function test_login() {
	    var_dump(11);exit();
    }

	//检查APP本地sign与数据库的sign是否一样，不一样即登录失效
	public function check_sign() {
		$id = intval($this->request->get('id'));
		$sign = trim($this->request->get('sign'));
		if ($id && $sign) {
			$member = SQL::share('member')->where("id='{$id}' AND sign='{$sign}'")->row();
			if ($member) {
				$_SESSION['member'] = $member;
				$this->_check_login();
				success($member);
			} else {
				if (!WX_MINIPROGRAM) {
					error("该账号已在其他设备登录", -9);
				} else {
					success(NULL);
				}
			}
		} else {
			//error("请登录", -100);
			if (!WX_MINIPROGRAM) {
				error("请登录");
			} else {
				success(NULL);
			}
		}
	}

	//检查手机是否被注册，以及发送注册验证码
	public function send_sms() {
		$mobile = trim($this->request->post('mobile'));
		if ($mobile) {
			$code = rand(1000,9999);
			send_sms($mobile, $code, 130636, 1);
			$_SESSION['login_sms_code'] = $code;
			$_SESSION['login_sms_mobile'] = $mobile;
			success(array("code"=>$code, "mobile"=>$mobile));
		} else {
			error("请输入合法手机号码");
		}
	}

	//检查手机是否被注册，以及发送注册验证码
	public function check_mobile() {
		$url = (isset($_REQUEST['url']) && trim($_REQUEST['url'])) ? trim($_REQUEST['url']) : '';
		$mobile = isset($_POST['mobile']) && $_POST['mobile'] ? $_POST['mobile'] : '';
		if ($mobile) {
			if (!SQL::share('member')->where("mobile='{$mobile}'")->exist()) {
				$code = rand(1000,9999);
				//$content = '您的手机注册验证码是'.$code.'。';
				send_sms($mobile, $code, 130636);
				$_SESSION['verify_code'] = $code;
				$_SESSION['verify_mobile'] = $mobile;
				success(array("code"=>$code, "mobile"=>$mobile));
			} else {
				error('手机号码已经被注册');
			}
		} else {
			error("请输入合法手机号码");
		}
	}

	//处理登录或注册后的操作
	private function _after_passport($member, $is_login=false, $is_register=false, $avatar='') {
		if (!$member && !is_object($member)) error('member is not an object');

		//生成签名
		if ($this->is_weixin() && $is_login) {
			$sign = $member->sign;
		} else {
			//20160322 by ajsong 不理是否微信登录都更新一下sign会好点
			$sign = generate_sign();
			$member->sign = $sign;
			SQL::share('member')->where($member->id)->update("sign='{$sign}'");
		}

		//设置登录信息
		$this->sign = $sign;
		if ($is_login) $this->_check_login();

		//$member->avatar = $this->get_avatar();
		if ($member->avatar) {
			$member->avatar = add_domain($member->avatar);
		} else {
			$member->avatar = add_domain("/images/avatar.jpg");
		}
		//生成缩略图
		//$member->avatar = $member->avatar."!logo";
		$member->format_reg_time = date('Y-m-d', $member->reg_time);
		$member = add_domain_deep($member, array("avatar"));
		
		//总财富
		$member->total_price = strval($member->money+$member->commission);

		//登录与注册都需要记录openid
		if (isset($_SESSION['openid'])) {
			SQL::share('member')->where($member->id)->update("openid='".$_SESSION['openid']."'");
		}

		//更新在线
		SQL::share('member')->where($member->id)->update("session_id='".session_id()."'");

		//更新购物车
		$sql = "UPDATE {$this->tbp}cart SET member_id='{$member->id}' WHERE session_id='".session_id()."'";
		$this->db->query($sql);

		//微信端跳转回之前查看的页面
		if ($this->is_weixin() && $is_login) {
			$url = (isset($_SESSION['weixin_url']) && trim($_SESSION['weixin_url'])) ? trim($_SESSION['weixin_url']) : 'wap.php';
			header("location:{$url}");
			exit;
		}

		//是否已绑定手机(账号)
		$member->is_mobile = !$member->name ? 0 : 1;
		
		if ($is_register) {
			//设置为最低等级
			$sql = "SELECT id FROM {$this->tbp}member_grade WHERE status=1 ORDER BY sort DESC, id DESC";
			$grade_id = intval($this->db->get_var($sql));
			if ($grade_id>0) SQL::share('member')->where($member->id)->update("grade_id='{$grade_id}'");
			$member->grade_id = $grade->id;
			$member->grade_score = $grade->score;
			//header("location:wap.php?tpl=register.complete");
			//exit;
		}
		
		//获取当前等级的下个等级
		$score = 0;
		$sql = "SELECT score FROM {$this->tbp}member_grade WHERE status=1 AND id>'{$member->grade_id}' ORDER BY sort ASC, id ASC";
		$row = $this->db->get_row($sql);
		if ($row) $score = intval($row->score);
		if ($score==0) {
			$sql = "SELECT score FROM {$this->tbp}member_grade WHERE id='{$member->grade_id}'";
			$score = intval($this->db->get_var($sql));
		}
		$member->next_score = "{$score}";
		$sql = "SELECT * FROM {$this->tbp}member_grade WHERE id='{$member->grade_id}'";
		$grade = $this->db->get_row($sql);
		$member->grade = $grade;
		$member = add_domain_deep($member, array('avatar', 'pic'));
		
		success($member);
	}

	//忘记密码 - 发送手机号码和验证短信
	public function forget_send_sms() {
		$mobile = isset($_POST['mobile']) && $_POST['mobile'] ? $_POST['mobile'] : '';
		if (!$mobile) erorr('请输入合法手机号码');
		$sql = "SELECT COUNT(*) FROM {$this->tbp}member WHERE mobile='{$mobile}'";
		$count = $this->db->get_var($sql);
		if ($count==1) {
			$code = rand(1000,9999);
			//$content = '您的手机验证码是'.$code.'。';
			//send_sms($mobile, $content);
			send_sms($mobile, $code, 130636);
			$_SESSION['forget_sms_mobile'] = $mobile;
			$_SESSION['forget_sms_code'] = $code;
			success(array('mobile'=>$mobile, 'code'=>$code));
		} else if ($count>1) {
			error('该手机号码被重复注册，无法找回密码，请联系管理员');
		} else {
			error('该手机号码没在系统注册');
		}
	}

	//忘记密码
	public function forget() {
		$mobile = (isset($_POST['mobile']) && $_POST['mobile']) ? $_POST['mobile'] : '';
		$code = (isset($_POST['code']) && $_POST['code']) ? $_POST['code'] : '';
		$password = (isset($_POST['password']) && $_POST['password']) ? $_POST['password'] : '';
		$forget_sms_code = (isset($_SESSION['forget_sms_code']) && $_SESSION['forget_sms_code']) ? $_SESSION['forget_sms_code'] : '';
		if (!$mobile || !$code || !$password) erorr('请提交手机、验证码和密码参数');
		if (!$forget_sms_code || $code!=$forget_sms_code) error('验证码不正确');
		$sql = "SELECT id, name, mobile FROM {$this->tbp}member WHERE mobile='{$mobile}'";
		$member = $this->db->get_row($sql);
		if (!$member) error('无此会员');
		$salt = generate_salt();
		$crypt_password = crypt_password($password, $salt);
		$sql = "UPDATE {$this->tbp}member SET password='{$crypt_password}', origin_password='{$password}', salt='{$salt}' WHERE id='{$member->id}'";
		$this->db->query($sql);
		//修改环信密码
		/*
		require_once(FRAMEWORK_PATH . "/class/emchat/Easemob.class.php");
		$options = array(
			"client_id" => $this->easemob_client_id,
			"client_secret" => $this->easemob_client_secret,
			"org_name" => $this->easemob_org_name,
			"app_name" => $this->easemob_app_name,
		);
		$easmob = new Easemob($options);
		$options = array(
			"username"=>$member->id,
			"newpassword"=>$password
		);
		$easmob->editPassword($options);
		*/
		//success($member->name, "修改密码成功，登录账号{$member->mobile}", '', '', 'wap.php?tpl=forget.complete');
		success('ok');
	}

	//退出
	public function logout(){
		$this->clearsession();
		location('http://www.hcshebao.com/');
		success("ok");
	}

	//清除session
	private function clearsession() {
		session_unset();
		if (isset($_SESSION['member'])) unset($_SESSION['member']);
		if (isset($this->member) && $this->member_id>0) $this->member_id = 0;
	}
 }
